package com.apes.fn.server.servicePlan.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.fn.mdm.purchase.PurchasingGroupRepository;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MD5Util;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.car.model.CarServiceLevel;
import com.apes.scm.masterdata.car.service.CarServiceLevelService;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.service.StoreService;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static java.util.Calendar.DAY_OF_MONTH;

/**
 * 类描述：
 *
 * @ClassName SantouliubiService
 * @Description 描述
 * @Author wushilong
 * @Date 2023/1/8 17:12
 * @Version 1.0
 */
@Service
public class SantouliubiService extends DomainService {

    @Autowired
    private ServicePlanRepository servicePlanRepository;

    @Autowired
    private ServiceToForeign serviceToForeign;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private PiManager piManager;

    /**
     * 向三头六臂发起询价，获取三头六臂报价结果
     *
     * @param servicePlan
     */
    public void santouInquireMainData(ServicePlan servicePlan) {
        JSONObject inquireData = new JSONObject();
        JSONArray data = new JSONArray();

        inquireData.put("store", servicePlan.getBelongDept());
        List levelId = servicePlanRepository.findLEVELID(servicePlan.getFnCustomerExpand().getJekunModelCode());
        if (levelId.isEmpty()) throw new RuntimeException("未获取到车型编号");
        inquireData.put("carExternalNumber", levelId.get(0));
        inquireData.put("id", servicePlan.getId());

        AtomicReference<String> XJDH = new AtomicReference<>("");

        servicePlan.getServicePlanItems().forEach(servicePlanItem -> {
            if ("009525".equals(servicePlanItem.getCategory().getId())) return;
            inquireData.put("category", servicePlanItem.getCategory());
            //获取三头六臂报价结果
            JSONObject result = null;
            try {
                result = JSON.parseObject(invoke("sp.santouEnquiry.santouEnquiry", inquireData));
            } catch (Exception e) {
                throw new RuntimeException("供应商询价平台正在升级！请稍后···");
            }


            //三头商品
            JSONArray body = result.getJSONObject("body").getJSONArray("result");
            if (Objects.isNull(body) || body.size() == 0) return;

            //遍历商品查询销售价格并写入询价执行表
            body.forEach(single -> {
                JSONObject santouProduct = (JSONObject) single;
                //根据第三方商品编码查询商品 - 未能通过第三方编码成功对照的商品，直接抛弃
                String productNumber = santouProduct.getString("productNumber");
                JSONObject message = SpringManager.getBean(PiManager.class).synErp("mdmSpxxService.accordToDSFBMFind",
                        MapUtil.mapper("DSFSPID", productNumber));

                //过滤掉无库存的商品，直接抛弃数据，不参与后续过程
                Integer quantity = santouProduct.getInteger("quantity");
                if (quantity <= 0 || "{}".equals(message.getString("obj"))) return;
                //成功对照的商品
                JSONObject product = JSON.parseObject(message.getString("obj"));
                Dept belongDept = servicePlan.getBelongDept();

                //生成唯一值
                String wyz = MD5Util.encrypt(Math.random() + servicePlanItem.getProduct().getId());
                //查询询价执行表是否有相同商品（同车牌，同商品，同供应商）
                JSONObject valid = piManager.synErp("scmGysxjdService.querySantouProduct",
                        MapUtil.mapper("SPID", product.getString("SPID"), "LYDJHM", servicePlan.getId(),
                                "MDID", belongDept.getOrigin(), "CPHM", servicePlan.getFnCustomerExpand().getCarLicense()));
                /*if ("{}".equals(valid.getString("obj"))){
                    //获取询价单号
                    if ("".equals(XJDH.get())) {
                        JSONObject json = piManager.synErp("scmGysxjdService.santouliubiGetGYSXJDH",
                                MapUtil.mapper("VALUE", null));
                        XJDH.set("ST" + json.getString("obj"));
                    }
                    //获取销售价格
                    JSONObject jsonObject = getretailPrice(servicePlan, servicePlanItem, product, belongDept);
                    //设置销售价格
                    Double[] price = getPrice(santouProduct, product, jsonObject);
                    //构造询价执行表数据
                    enquiryExecute(servicePlan, data, servicePlanItem, XJDH.get(), wyz, santouProduct, product, belongDept, price);
                } else {
                    //获取销售价格
                    JSONObject jsonObject = getretailPrice(servicePlan, servicePlanItem, product, belongDept);
                    //设置销售价格
                    Double[] price = getPrice(santouProduct, product, jsonObject);
                    //更新询价执行表价格
                    updateEnquiry(servicePlan, price, product, santouProduct, belongDept);
                }*/

            });
        });
        //写入询价执行表
        piManager.synErp("scmGysxjdService.santouliubiSaveSPXJDZXB",
                MapUtil.mapper("item", data));
    }

    /**
     * 设置销售价格
     *
     * @param santouProduct 三头六臂商品信息
     * @param product       商品信息
     * @param retailPrice    销售价格
     * @return
     */
    private Double getPrice(JSONObject santouProduct, Product product, JSONObject retailPrice) {
        //设置销售限价
        Double price = 0.0;//销售单价
        if (retailPrice.getDouble("pftPriceUnit") > 0.0) {
            price = retailPrice.getDouble("primaryPriceUnit");
        }

        //没有销售价格文件则走加价规则
        if (price == 0.0) {
            JSONObject obj = this.invoke("scm.externalInquiry.newSystemPrice", MapUtil.mapper("P001", santouProduct.getString("salePrice"), "PRODUCT_ID", product.getId(),
                    "CLASSIFY_ID", product.getClassify().getId(), "BRAND_ID", product.getBrand().getId(), "SYS_RQ", new Date()));
            price = obj.getDouble("XSDJ");
        }
        return price;
    }

    /**
     * @param fnCustomerExpand 客户扩展信息
     * @param product         商品信息
     * @param belongDept      门店
     * @return 销售价格
     */
    public JSONObject getRetailPrice(FnCustomerExpand fnCustomerExpand, Product product, Dept belongDept) {
        //查询价格文件,获取销售价格
        JSONObject jsonObject = serviceToForeign.getXS51(
                MapUtil.mapper(
                        "uniqueIdentify", product.getId(),
                        "SPMC", product.getName(),
                        "MDID", belongDept.getId(),
                        "PLID", product.getClassify().getId(),
                        "SPID", product.getId(),
                        "HZLXID", null,
                        "PPID", product.getBrand().getId(),
                        "PZID", product.getBrand().getQuality() == null ? null : product.getBrand().getQuality().getId(),
                        "XSZZID", belongDept.getCompany().getId(),
                        "GSID", belongDept.getCompany().getId(),
                        "FNKHID", fnCustomerExpand.getUnitClientId(),
                        "CLFWDJID", ((CarServiceLevel) (SpringManager.getBean(CarServiceLevelService.class).findByCarConfigurationId(fnCustomerExpand.getJekunModelCode()))).getId(),
                        //"MDLXID", belongDept.getDeptType().getId(),
                        "FNVIPJBID", fnCustomerExpand.getCustomerLevelId(),
                        "FNVIPSFID", fnCustomerExpand.getUserRoleId(),
                        "CGZZID", getBean(PartyRoleRepository.class).findOne("1001").getId(),
                        "JLDW", product.getUom().getName(),
                        "JLDWID", product.getUom().getId(),
                        "JRS", fnCustomerExpand.getVendorCode(),
                        "SJHM", fnCustomerExpand.getMobile(),
                        "XSMD", belongDept.getId(),
                        "YYMS", belongDept.getCompany().getParty().getCorporate().getOperation().getCode(),
                        "NYYMS", belongDept.getCompany().getParty().getCorporate().getOperation().getId(),
                        "CPHM", fnCustomerExpand.getCarLicense(),
                        "SQID", SpringManager.getBean(StoreService.class).findBusinessCircleByDept(belongDept).getId(),
                        "XYGSID", belongDept.getCompany().getId(),
                        "KYS", 0
                ), true
        );
        return jsonObject;
    }

    /**
     * 更新询价执行表信息
     * @param servicePlan 服务方案单
     * @param price 销售价格
     * @param product 商品
     * @param santouProduct 三头商品
     * @param belongDept 门店
     */
    private void updateEnquiry(ServicePlan servicePlan, Double[] price, JSONObject product, JSONObject santouProduct, Dept belongDept) {
        JSONObject json = new JSONObject();
        json.put("CGDJ", santouProduct.getString("salePrice"));
        json.put("XSXJ", price[0]);//销售限价
        json.put("XSDJ", price[1]);//销售单价
        json.put("SPID", product.getString("SPID"));
        json.put("LYDJHM", servicePlan.getId());//来源单据号码
        json.put("MDID", belongDept.getOrigin());
        json.put("CPHM", servicePlan.getFnCustomerExpand().getCarLicense());//车牌号码
        Date date = new Date();
        Date YXQZ = DateUtil.add(date, DAY_OF_MONTH, 3);//系统时间+3天
        json.put("YXQZ", DateUtil.format(YXQZ, DateUtil.SHOW_DATE_FORMAT));//有效期止

        Date XJBLQ = DateUtil.add(date, DAY_OF_MONTH, 30);
        json.put("XJBLQ", DateUtil.format(XJBLQ, DateUtil.SHOW_DATE_FORMAT));//询价保留期
        SpringManager.getBean(PiManager.class).synErp("scmGysxjdService.updateSPXJDZXBCGDJ", json);
    }

    /**
     * 构造询价执行表数据
     *
     * @param servicePlan     服务方案单
     * @param data            询价执行表列表
     * @param servicePlanItem 服务方案明细
     * @param XJDH            询价单号
     * @param wyz             唯一值
     * @param santouProduct   三头商品
     * @param SPXX         商品信息
     * @param belongDept      门店
     * @param price           销售价格
     */
    private void enquiryExecute(ServicePlan servicePlan, JSONArray data, ServicePlanItem servicePlanItem, String XJDH, String wyz, JSONObject santouProduct, JSONObject SPXX, Dept belongDept, Double[] price) {
        //拼装写入询价执行表的数据
        JSONObject execute = new JSONObject();
        execute.put("XJDH", XJDH);//询价单号
        execute.put("SPID", SPXX.getString("SPID"));//商品id
        execute.put("SPMC", SPXX.getString("SPMC"));//商品名称
        execute.put("PPID", SPXX.getString("PPID"));//品牌编码
        execute.put("PPMC", SPXX.getString("PPMC"));//品牌名称
        execute.put("CJID", SPXX.getString("CJID"));//厂家编码
        execute.put("CJMC", SPXX.getString("CJMC"));//厂家名称
        execute.put("SPZID", SPXX.getString("SPZID"));//商品组编码
        execute.put("SPZMC", SPXX.getString("SPZMC"));//商品组名称
        execute.put("SPXH", SPXX.getString("SPXH"));//商品型号
        execute.put("PLID", SPXX.getString("PLID"));//商品品类编码
        execute.put("PLMC", SPXX.getString("PLMC"));//商品品类名称
        execute.put("YSPID", servicePlanItem.getProduct().getId());//原商品ID
        execute.put("YSPMC", servicePlanItem.getProduct().getName());//原商品名称

        execute.put("HYZT", 1);//货源状态（0:无货;1:现货;2:需订货）
        execute.put("YJDHTS", 0);//预计到货天数
        execute.put("GYSID", "00006989");//供应商编码
        execute.put("GYSMC", "广东三头六臂信息科技有限公司(经销)服务站");//供应商名称

        execute.put("CGDJ", santouProduct.getString("salePrice"));//采购单价
        execute.put("XSXJ", price[0]);//销售限价
        execute.put("XSDJ", price[1]);//销售单价
        Date date = new Date();
        Date YXQZ = DateUtil.add(date, DAY_OF_MONTH, 3);//系统时间+3天
        execute.put("YXQZ", DateUtil.format(YXQZ, DateUtil.SHOW_DATE_FORMAT));//有效期止

        Date XJBLQ = DateUtil.add(date, DAY_OF_MONTH, 30);
        execute.put("XJBLQ", DateUtil.format(XJBLQ, DateUtil.SHOW_DATE_FORMAT));//询价保留期
        execute.put("JGYXQ", 3);//价格有效期
        Product product = productRepository.findOne(SPXX.getString("SPID"));
        PartyRole platform = getBean(PartyRoleRepository.class).findOne("1001");
        execute.put("PTID", platform.getId());//平台编码
        execute.put("PTMC", platform.getName());//平台名称
        execute.put("ZDID", "");//站点编码
        execute.put("ZDMC", "");//站点名称
        execute.put("LYDJHM", servicePlan.getId());//来源单据名称
        execute.put("LYDJLX", servicePlan.getBusinessType());//来源单据类型
        execute.put("CGZID", "0241");//采购组编码
        execute.put("CGZMC", "三头六臂采购组");//采购组名称
        execute.put("CGZZID", platform.getId());//采购组织编码
        execute.put("CGZZMC", platform.getName());//采购组织名称
        execute.put("WYZ", wyz);//唯一值
        execute.put("JLDW", SPXX.getString("CGDW"));
        execute.put("GSID", belongDept.getCompany().getId());
        execute.put("CJHM", servicePlan.getFnCustomerExpand().getVin());//车架号码
        execute.put("CPHM", servicePlan.getFnCustomerExpand().getCarLicense());//车架号码
//            execute.put("PART_NAME", StringUtils.hasText(modifiedPartsName)?partsName:modifiedPartsName);
        execute.put("YXSDJ2", 0);
        execute.put("XSSL", 0);
        execute.put("XSJS", 0);
        execute.put("SB", 0);
        execute.put("QRXZBJ", 1);
        execute.put("SLDS", 0);
        execute.put("LRL", 0);
        execute.put("XSXJ2", 0);
        execute.put("CBCYL", 0);
        execute.put("FXTTJBJ", 0);
        execute.put("WCBJ", 1);
        execute.put("BXDSDJ", 0);
        execute.put("XJLX", 1);
        execute.put("XS4S", 0);
        execute.put("LRL2", 0);
        execute.put("XSDJ2", 0);
        execute.put("KJHJS", 0);
        execute.put("MDID", belongDept.getOrigin());//门店编码
        execute.put("MDMC", belongDept.getName());//门店编码
        execute.put("FWFAH", servicePlan.getId());//服务方案号

        data.add(execute);
    }

    /**
     * 获取三头六臂商品列表
     * @param request
     * @return
     */
    public Map santouInquireProduct(SimpleRequest request){
        JSONObject requestJO = request.getJO();
        //三头六臂采购组才可以选择三头六臂的商品
        String deptId = "";
        if (StringUtils.isNotEmpty(requestJO.getString("saleDept"))){
            deptId = requestJO.getJSONObject("saleDept").getString("id");
        }
        if (StringUtils.isNotEmpty(requestJO.getString("lossDept"))){
            deptId = requestJO.getJSONObject("lossDept").getString("id");
        }
        Dept dept = getBean(DeptRepository.class).findOne(deptId);
        if (Objects.isNull(dept) || !purchasingGroup(dept)){
            return MapUtil.mapper("content", new JSONArray(), "page", requestJO.getInteger("page"), "size", requestJO.getInteger("size"),"total", 0);
        }
        requestJO.put("deptId", deptId);
        //获取车型信息
        FnCustomerExpand fnCustomerExpand = getBean(PriceForwardService.class).getFnCustomerExpand(requestJO.getString("carLicense"), "");
        List levelId = servicePlanRepository.findLEVELID(fnCustomerExpand.getJekunModelCode());
        if (levelId.isEmpty()) throw new RuntimeException("未获取到车型编号");
        requestJO.put("carExternalNumber", levelId.get(0));

        //按每个字模糊
        String likeName = getLikeName(requestJO.getString("keywords").toCharArray());
        //获取三头六臂配件编码
        BusinessParam businessParam = getBean(BusinessParamRepository.class).findOne("20");
        List<String> productNumbers = new ArrayList<>();
        if ("pro".equals(businessParam.getValue())){
            productNumbers = productRepository.findByThirdParty(likeName);
        }else {
            productNumbers = productRepository.findByThirdPartyTest(likeName);
        }
        if (productNumbers.isEmpty() && "yes".equals(requestJO.getString("relationType"))) return MapUtil.mapper("content", new ArrayList<>(), "page", requestJO.getInteger("page"), "size", requestJO.getInteger("size"),"total", 0);
        requestJO.put("productNumber", productNumbers);

        //获取三头六臂商品信息
        JSONObject body = getResult(requestJO);
        if (body.isEmpty() || Objects.nonNull(body.get("error"))) return MapUtil.mapper("content", new ArrayList<>(), "page", requestJO.getInteger("page"), "size", requestJO.getInteger("size"),"total", 0);

        //处理三头返回数据
        JSONObject result = group(body);
        JSONArray items = result.getJSONArray("items");
        JSONArray product = addField(items, body);
        return MapUtil.mapper("content", product, "page", requestJO.getInteger("page"), "size", requestJO.getInteger("size"),"total", result.getInteger("count"));

    }

    //按每个字模糊查询（示例：%1%2%3%）
    private String getLikeName(char... name){
        StringBuilder likeName = new StringBuilder();
        for (int i = 0; i <= name.length-1; i++) {
            likeName.append("%"+name[i]);
            if (name.length-1 == i){
                likeName.append("%");
            }
        }
        return likeName.toString();
    }

    private boolean purchasingGroup(Dept dept){
        List<String> santouPurchasingGroup = getBean(PurchasingGroupRepository.class).accordingPurchasingGroupGetDeptId("三头六臂采购组");
        return santouPurchasingGroup.contains(dept.getId());
    }

    //调用供应商平台获取商品价格信息
    private JSONObject getResult(JSONObject requestJO) {
        JSONObject result;
        try {
            //匹配和不匹配车型
            if ("yes".equals(requestJO.getString("relationType"))){
                //不匹配车型
                result = JSON.parseObject(invoke("sp.santouEnquiry.santouProductData", requestJO));
            }else {
                //匹配车型
                result = JSON.parseObject(invoke("sp.santouEnquiry.vinSantouProductData", requestJO));
            }
        } catch (Exception e) {
            throw new RuntimeException("供应商询价平台正在升级！请稍后···");
        }
        return result.getJSONObject("body");
    }

    //匹配车型和不匹配车型响应结果不同，将响应结果封装成一样的
    private JSONObject group(JSONObject body){
        //不匹配车型
        if (body.get("result") instanceof JSONObject){
            JSONObject result = body.getJSONObject("result");
            result.getJSONArray("items").forEach(o -> {
                JSONObject item = (JSONObject) o;
                JSONObject message = SpringManager.getBean(PiManager.class).synErp("mdmSpxxService.accordToDSFBMFind",
                        MapUtil.mapper("DSFSPID", item.getString("productNumber")));
                item.put("SPID", message.getJSONObject("obj").getString("SPID"));
            });
            return body.getJSONObject("result");
        }
        //匹配车型
        JSONObject result = new JSONObject();
        JSONArray items = body.getJSONArray("result").stream().filter(item -> filterProduct((JSONObject) item)).collect(Collectors.toCollection(JSONArray::new));
        result.put("items", items);
        result.put("count",items.size());
        return result;
    }

    //前端要求添加的字段
    private JSONArray addField(JSONArray items, JSONObject body){
        items.forEach(item ->{
            JSONObject productData = (JSONObject) item;
            productData.put("id", productData.getString("productNumber"));
            productData.put("supplier", "三头六臂");
            productData.put("source", "santou");
            productData.put("specification", productData.getString("supplierNumber"));
            productData.put("merchantsId", body.getString("merchantsId"));
        });
        return items;
    }

    /**
     * 获取销售价格
     * @param request
     */
    public Map marketPrice(SimpleRequest request){
        JSONObject requestJO = request.getJO();
        //三头六臂采购组才可以选择三头六臂的商品
        String deptId = "";
        if (StringUtils.isNotEmpty(requestJO.getString("saleDept"))){
            deptId = requestJO.getJSONObject("saleDept").getString("id");
        }
        if (StringUtils.isNotEmpty(requestJO.getString("lossDept"))){
            deptId = requestJO.getJSONObject("lossDept").getString("id");
        }
        Dept dept = getBean(DeptRepository.class).findOne(deptId);
        if (Objects.isNull(dept) || !purchasingGroup(dept)){
            return MapUtil.mapper("content", new JSONArray(), "page", requestJO.getInteger("page"), "size", requestJO.getInteger("size"),"total", 0);
        }
        requestJO.put("deptId", deptId);

        //获取车型信息
        FnCustomerExpand fnCustomerExpand = getBean(PriceForwardService.class).getFnCustomerExpand(requestJO.getString("carLicense"),"");
        List levelId = servicePlanRepository.findLEVELID(fnCustomerExpand.getJekunModelCode());
        if (levelId.isEmpty()) throw new RuntimeException("未获取到车型编号");
        requestJO.put("carExternalNumber", levelId.get(0));


        //按每个字模糊
        String likeName = getLikeName(requestJO.getString("keywords").toCharArray());
        //获取三头六臂配件编码
        BusinessParam businessParam = getBean(BusinessParamRepository.class).findOne("20");
        List<String> productNumbers = new ArrayList<>();
        if ("pro".equals(businessParam.getValue())){
            productNumbers = productRepository.findByThirdParty(likeName);
        }else {
            productNumbers = productRepository.findByThirdPartyTest(likeName);
        }
        if (productNumbers.isEmpty() && "yes".equals(requestJO.getString("relationType"))) return MapUtil.mapper("content", new ArrayList<>(), "page", requestJO.getInteger("page"), "size", requestJO.getInteger("size"),"total", 0);
        requestJO.put("productNumber", productNumbers);

        //获取三头六臂商品信息
        JSONObject body = getResult(requestJO);
        if (body.isEmpty() || Objects.nonNull(body.get("error"))) return MapUtil.mapper("content", new ArrayList<>(), "page", requestJO.getInteger("page"), "size", requestJO.getInteger("size"),"total", 0);


        //处理三头返回数据，通过成本价算出售价
        JSONObject result = group(body);
        JSONArray items = result.getJSONArray("items");

        //获取商品销售价格
        List<Map> prices = getPrices(items, fnCustomerExpand, dept, businessParam.getValue());

        return MapUtil.mapper("content", prices, "page", requestJO.getInteger("page"), "size", requestJO.getInteger("size"), "total", result.getInteger("co商品信息unt"));
    }

    //获取商品销售价格
    //items:三头六臂商品集合
    private List<Map> getPrices(JSONArray items,FnCustomerExpand fnCustomerExpand, Dept dept, String environment) {

        return items.stream().filter(item -> filterProduct((JSONObject) item)).map(item -> {
            JSONObject productData = (JSONObject) item;
            Product product;
            if ("pro".equals(environment)) {
                product = productRepository.findByThirdPartyId(productData.getString("productNumber"));
            } else {
                product = productRepository.findByThirdPartyIdTest(productData.getString("productNumber"));
            }
            //没有对照关系的商品取不到价格
            if (Objects.isNull(product)) return MapUtil.mapper("productNumber", productData.getString("productNumber"), "priceSuggested", null);
            JSONObject retailPrice = getRetailPrice(fnCustomerExpand, product, dept);
            double price = getPrice(productData, product, retailPrice);

            return MapUtil.mapper("productNumber", productData.getString("productNumber"), "priceSuggested", twoDecimalPlaces(price));
        }).collect(Collectors.toList());
    }

    //过滤没有匹配关系的商品
    private boolean filterProduct(JSONObject productData){
        //根据第三方商品编码查询商品 - 未能通过第三方编码成功对照的商品，直接抛弃
        String productNumber = productData.getString("productNumber");
        JSONObject message = SpringManager.getBean(PiManager.class).synErp("mdmSpxxService.accordToDSFBMFind",
                MapUtil.mapper("DSFSPID", productNumber));

        //过滤掉无库存的商品，直接抛弃数据，不参与后续过程
        Integer quantity = productData.getInteger("quantity");
        boolean valid = !(quantity <= 0 || "{}".equals(message.getString("obj")));
        if (valid){
            productData.put("SPID", message.getJSONObject("obj").getString("SPID"));
        }
        return valid;
    }

    /**
     * 固定小数点点后两位
     *
     * @param old
     * @return
     */
    private String twoDecimalPlaces(Double old) {
        long round = Math.round(old);
        DecimalFormat df = new DecimalFormat("#0.00");
        return df.format(round);
    }

}
